/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agenda.database;

import agenda.entityes.TelNumber;
import agenda.entityes.AgeEntry;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 *
 * @author emanuele
 */
public class DBWriter {

    private static final String HEADER = "#";
    private static final String ID = "ID";
    private static final String TAZIENDA = "AZ";
    private static final String TPERSONA = "PE";
    private static final String NOME = "NM";
    private static final String COGNOME = "SN";
    private static final String EMAIL = "EM";
    private static final String DESCRIZIONE = "DS";
    private static final String PT_ABITAZIONE = "AB";
    private static final String PT_UFFICIO = "UF";
    private static final String PT_CELLULARE = "CE";
    private static final String PT_FAX = "FA";
    private static final String LINK = "LK";
    private static final String STRDELIM = "\"";

    private static  String entryToLine(AgeEntry e) {
        StringBuilder sb = new StringBuilder();
        // appendi l'ID
        sb.append((ID + e.getID()));
//appendi il tipo
        sb.append(e.getType() == AgeEntry.Type.Azienda? TAZIENDA : TPERSONA);

//appendi il nome se presente
        if (e.getName() !=null && !e.getName().isEmpty())
        sb.append(NOME + STRDELIM + e.getName() + STRDELIM);
 //appendi il cognome
        sb.append(COGNOME + STRDELIM + e.getSurname() + STRDELIM);
//appendi l'email se presente
        if (e.getEmail() !=null && !e.getEmail().isEmpty())
           sb.append(EMAIL + STRDELIM + e.getEmail() + STRDELIM);
///appendi descrizione se presente
        if (e.getDesc() !=null && !e.getDesc().isEmpty())
           sb.append(DESCRIZIONE + STRDELIM + e.getDesc() + STRDELIM);
//appendi i numeri di telefono
        for (TelNumber x : e.getNumbers()){
            sb.append((x.getType() == TelNumber.Type.Ufficio? PT_UFFICIO:
                    x.getType() == TelNumber.Type.Cellulare? PT_CELLULARE:
                    x.getType() == TelNumber.Type.Fax? PT_FAX: PT_ABITAZIONE)
                    + x.num );
        }
//appendi i link se presenti
        if (e.getAssociations().size() > 0)
            sb.append(LINK );
        for (AgeEntry x : e.getAssociations()){
            sb.append(STRDELIM + x.getID() + STRDELIM );
        }

        return sb.toString();
    }

    public static void writeToFile(AgeDB db, File f) throws FileNotFoundException {
        if (f == null || db == null) {
            throw new IllegalArgumentException();
        }

        PrintStream ps = new PrintStream(f);
//        ps.println(HEADER + AgeEntry.nextID);
        for (AgeEntry x : db.entries){
            ps.println(entryToLine(x));
        }
    }
}
